package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.gateway.form.shopping.AddCartForm;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.ITokenToUserIdService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName CartController
 * @Description
 * @Author 王昀昊
 * @Date 2021/8/24 22:46
 * @Version 1.0
 **/
@RequestMapping("shopping")
@RestController
public class CartController {

    @Reference(timeout = 3000,retries = 0,check = false)
    ICartService cartService;

//    @Reference(timeout = 3000,retries = 0,check = false)
//    ITokenToUserIdService tokenToUserIdService;

    /**
     * 获得购物车列表
     * @return
     */
    @GetMapping("carts")
    public ResponseData getCartList(HttpServletRequest request){
        long userId = getUserId(request);
        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();
        cartListByIdRequest.setUserId(userId);
        CartListByIdResponse cartListById = cartService.getCartListById(cartListByIdRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(cartListById.getCode())){
            //调用成功
            return new ResponseUtil().setData(cartListById.getCartProductDtos());
        }
        return new ResponseUtil().setErrorMsg(cartListById.getMsg());
    }

    /**
     * 添加商品到购物车
     * @param addCartForm
     * @return
     */
    @PostMapping("carts")
    public ResponseData addItemToCart(@RequestBody AddCartForm addCartForm, HttpServletRequest request){
        AddCartRequest cartRequest = new AddCartRequest();
        cartRequest.setUserId(addCartForm.getUserId());
        cartRequest.setItemId(addCartForm.getProductId());
        cartRequest.setNum(addCartForm.getProductNum());
//        long userId = getUserId(request);
        AddCartResponse addCartResponse = cartService.addToCart(cartRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(addCartResponse.getCode())){
            //调用成功
            return new ResponseUtil().setData("成功");
        }
        return new ResponseUtil().setErrorMsg(addCartResponse.getMsg());
    }

    private long getUserId(HttpServletRequest request) {
        //获取Token
        //也就是从request域中获取用户信息userInfo
//        String token = CookieUtil.getCookieValue(request, "access_token");
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);

        //获取用户id
//        Long userId = tokenToUserIdService.getUserId(token);
        Object user = JSON.parseObject(userInfo);
        String id = ((JSONObject) user).get("uid").toString();
        long userId = Long.parseLong(id);
        return userId;
    }




    /**
     * zmc
     * change the checked status about the item of cart
     */
    @PutMapping("/carts")
    public ResponseData cartCheck(HttpServletRequest request, @RequestBody Map<String,Object> map){

        //put the user info into updateCartNumRequest
        UpdateCartNumRequest updateCartNumRequest = new UpdateCartNumRequest();
        updateCartNumRequest.setUserId(Long.valueOf(map.get("userId").toString()));
        updateCartNumRequest.setItemId(Long.valueOf(map.get("productId").toString()));
        updateCartNumRequest.setChecked(map.get("checked").toString());
        updateCartNumRequest.setNum(((Integer) map.get("productNum")));

        UpdateCartNumResponse response = cartService.updateCartNum(updateCartNumRequest);

        //get response
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData("成功");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 张明臣
     * 删除购物车中的商品
     */
    @DeleteMapping("/carts/**")
    public ResponseData cartDelete(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        //分隔uri获取对应id
        String[] split = requestURI.split("/");
        //创建requst并进行赋值
        DeleteCartItemRequest deleteCartItemRequest = new DeleteCartItemRequest();

        deleteCartItemRequest.setUserId(Long.valueOf(split[3]));
        deleteCartItemRequest.setItemId(Long.valueOf(split[4]));

        DeleteCartItemResponse response = cartService.deleteCartItem(deleteCartItemRequest);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData("成功");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 张明臣
     * 删除购物车中选择的商品
     */
    @DeleteMapping("/items/*")
    public ResponseData itemDelete (HttpServletRequest request){
        String requestURI = request.getRequestURI();
        //分隔uri获取对应id
        String[] split = requestURI.split("/");
        DeleteCheckedItemRequest itemRequest = new DeleteCheckedItemRequest();
        itemRequest.setUserId(Long.valueOf(split[3]));

        DeleteCheckedItemResposne response = cartService.deleteCheckedItem(itemRequest);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData("成功");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 张明臣
     * cart checked 全选 全不选
     */
    @PutMapping("/items")
    public ResponseData checkedAllOrNot (HttpServletRequest request,@RequestBody Map<String,Object> map){

        CheckAllItemRequest itemRequest = new CheckAllItemRequest();
        itemRequest.setUserId(Long.valueOf(map.get("userId").toString()));
        itemRequest.setChecked(map.get("checked").toString());

        CheckAllItemResponse response = cartService.checkAllCartItem(itemRequest);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil().setData("成功");
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

}
